package com.catcoin.deposit.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.catcoin.deposit.aliyun.OSSResultModel;
import com.catcoin.deposit.model.Account;
import com.catcoin.deposit.model.Inviteid;
import com.catcoin.deposit.model.User;
import com.catcoin.deposit.mapper.UserMapper;
import com.catcoin.deposit.model.UserDto;
import com.catcoin.deposit.result.Result;
import com.catcoin.deposit.service.IAccountService;
import com.catcoin.deposit.service.IInviteidService;
import com.catcoin.deposit.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.catcoin.deposit.service.ToolfeignInterface;
import com.catcoin.deposit.util.CacheUtil;
import com.catcoin.deposit.util.FileUtils;
import com.catcoin.deposit.util.MD5Util;
import com.catcoin.deposit.util.MSGUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author caody
 * @since 2018-08-31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    ToolfeignInterface toolfeignInterface;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IInviteidService inviteidService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private FileUtils fileUtils;

    @Override
    public Map<String,Object> login(@PathVariable String userphone, String password){
        Map<String,Object> map=new HashMap<>();
        EntityWrapper wrapper=new EntityWrapper();
        wrapper.setEntity(new User());
        wrapper.where("userPhone={0}", userphone).orNew("userName={0}", userphone);
        User user1 = this.selectOne(wrapper);
        //        User user=new User();
//        user.setUserPhone(userphone);
//        EntityWrapper<User> entityWrapper=new  EntityWrapper<User>(user);
//        User user1 = this.selectOne(entityWrapper);
        if (user1==null){
            map.put("code","00");
            map.put("msg","该账户不存在，请您注册");
            return map;
        }
        Integer salt = user1.getSalt();
        String newPassword=password+salt;
        String md5Result = MD5Util.encrypt(newPassword);
        EntityWrapper wp=new EntityWrapper();
        wp.setEntity(new User());
        wp.where("password={0}",md5Result).andNew("userPhone={0}", userphone).or("userName={0}", userphone);
        User newUser1 = this.selectOne(wp);
//        User newUser=new User();
//        newUser.setUserPhone(userphone);
//        newUser.setPassword(md5Result);
//        EntityWrapper<User> ew=new  EntityWrapper<User>(newUser);
//        User newUser1 = this.selectOne(ew);
        if(newUser1==null){
            map.put("code","00");
            map.put("msg","账户名或密码错误，请重新登录");
            return map;
        }
        if (newUser1.getUserStatus()==0){
            map.put("code","00");
            map.put("msg","该用户已被锁定");
            return map;
        }
        Integer userId=newUser1.getUserId();
//        User user = this.selectById(userId);
        Map<String, Object> mmp = userMapper.selectLoginMessages(userId);
        //获取交易所用户id
        String userPhone = mmp.get("userPhone").toString();
        String result = toolfeignInterface.getHHTBUserId(userPhone);
        String HHTBId="";
        if (!"error".equals(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            if("true".equals(jsonObject.get("isSuc").toString())){
                JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("datas").toString());
                HHTBId=  jsonObject1.get("userID").toString();
            }
        }

//        UserDto userDto=new UserDto();
//        BeanUtils.copyProperties(newUser1,userDto);
        Object payPwd = mmp.get("payPwd");
        if(payPwd != null && !"".equals(payPwd.toString())){
            mmp.put("isppwd",true);
        }else {
            mmp.put("isppwd",false);
        }
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format((Date)mmp.get("createTime"));
        mmp.put("createTime",format);
//        userDto.setHhtbId(HHTBId);
        mmp.put("HHTBId",HHTBId);
        cacheUtil.set("catCoinUserId",userId);
        cacheUtil.set("catCoinUserName",newUser1.getUserName());
//        map.put("user",userDto);
        mmp.put("code","01");
        mmp.put("msg","登录成功");
        return mmp;
    }
    //验证分享人的信息
    @Override
    public Map<String,Object> findShare(String checkData){
        Map<String,Object> map=new HashMap<>();
        EntityWrapper ew=new EntityWrapper();
        ew.setEntity(new User());
        ew.where("userPhone={0}", checkData).orNew("userName={0}", checkData);
        User user = this.selectOne(ew);
        if (user==null){
            map.put("code","00");
            map.put("msg","验证信息有误");
            return map;
        }

        //验证手机号工具
        //判断是否是手机号
        boolean responsePhone = MSGUtil.getResponsePhone(checkData);
        if (responsePhone) {
            map.put("shareInfo",user.getUserName());
        }else {
            map.put("shareInfo",user.getUserPhone());
        }
        return map;
    }

    @Override
    @Transactional
    public  Map<String,Object> regist(String loginName, String num,  String userPhone,  String checkData,  String loginPwd){
        Map<String,Object> map=new HashMap<>();
        try {
            if(loginName == null || "".equals(loginName)){
                map.put("code","00");
                map.put("msg","用户名不能为空");
                return map;
            }
            EntityWrapper ew=new EntityWrapper();
            ew.setEntity(new User());
            ew.where("userPhone={0}", loginName).orNew("userName={0}", loginName);
            User user1 = this.selectOne(ew);
            if (user1!=null ){
                map.put("code","00");
                map.put("msg","该用户名已存在");
                return map;
            }
            EntityWrapper ewp=new EntityWrapper();
            ewp.setEntity(new User());
            ewp.where("userPhone={0}", userPhone).orNew("userName={0}", userPhone);
            User user2 = this.selectOne(ewp);
            if (user2!=null ){
                map.put("code","00");
                map.put("msg","该手机号已存在");
                return map;
            }

            //从缓存中获取短信验证码
            Object obj = cacheUtil.get("mb:"+userPhone);
            if(obj != null){
                if(!obj.toString().equals(num)){
                    map.put("code","00");
                    map.put("msg","短信验证码错误");
                    return map;
                }
            }else {
                map.put("code","00");
                map.put("msg","短信验证码失效");
                return map;
            }

            //生成salt
            Random random = new Random();
            String secret = "";
            for (int i = 0; i < 4; i++) {
                secret += random.nextInt(10);
                if (secret.length() == 1 && secret.equals("0")) {
                    secret = random.nextInt(9) + 1 + "";
                }
            }

            //在user表生成数据
            User user = new User();
            user.setCreateTime(new Date());
            user.setIsOperation(1);
            //密码加盐
            String password = loginPwd+secret;
            //md5加密密码
            password = MD5Util.encrypt(password);
            user.setPassword(password);
            user.setSalt(Integer.parseInt(secret));
            user.setUserName(loginName);
            user.setUserPhone(userPhone);
            user.setUserStatus(1);
            user.setUserType(0);
            boolean b = this.insert(user);
            if(!b){
                map.put("code","00");
                map.put("msg","注册失败");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return map;
            }

            //推荐表生成数据
            Inviteid inviteid = new Inviteid();
            inviteid.setUserId(user.getUserId());
            inviteid.setUserPhone(user.getUserPhone());
            //判断推荐人信息是否为空
            if(checkData != null && !"".equals(checkData)){
                //不为空
                EntityWrapper ew2=new EntityWrapper();
                ew2.setEntity(new User());
                ew2.where("userPhone={0}", checkData).orNew("userName={0}", checkData);
                //查询推荐人信息
                User user3 = this.selectOne(ew2);
                if(user3 != null){
                    inviteid.setInviteId(user3.getUserId());
                    inviteid.setInvitePhone(user3.getUserPhone());
                }
            }
            boolean b1 = inviteidService.insert(inviteid);
            if(!b1){
                map.put("code","00");
                map.put("msg","生成推荐失败");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return map;
            }

            //生成账户数据
            Account account = new Account();
            account.setUserId(user.getUserId());
            account.setStatus(1);
            boolean b2 = accountService.insert(account);
            if(!b2){
                map.put("code","00");
                map.put("msg","生成账户失败");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return map;
            }

            /**
             * 注册成功返回
             */

            //获取交易所用户id
            String result = toolfeignInterface.getHHTBUserId(user.getUserPhone());
            String HHTBId="";
            if (!"error".equals(result)){
                JSONObject jsonObject = JSONObject.parseObject(result);
                if("true".equals(jsonObject.get("isSuc").toString())){
                    JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("datas").toString());
                    HHTBId=  jsonObject1.get("userID").toString();
                }
            }
            Map<String, Object> mmp = userMapper.selectLoginMessages(user.getUserId());
//            UserDto userDto=new UserDto();
//            BeanUtils.copyProperties(user,userDto);
            Object payPwd = mmp.get("payPwd");
            if(payPwd != null && !"".equals(payPwd.toString())){
                mmp.put("usppwd",true);
//                userDto.setIsppwd(true);
            }else {
                mmp.put("usppwd",false);
//                userDto.setIsppwd(false);
            }
//            Date createTime = user.getCreateTime();
            SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dateFormat.format((Date) mmp.get("createTime"));
//            userDto.setCreatetimes(format);
            mmp.put("createTime",format);
//            userDto.setHhtbId(HHTBId);
            mmp.put("HHTBId",HHTBId);

            //将用户信息存入缓存
            cacheUtil.set("catCoinUserId",user.getUserId());
            cacheUtil.set("catCoinUserName",user.getUserName());

//            map.put("user",userDto);
            mmp.put("code","01");
            mmp.put("msg","登录成功");
            return mmp;
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            map.put("code","00");
            map.put("msg","出错了");
            return map;
        }
    }
    @Override
    public Map<String,Object> getBalnce(String userId){
        Map<String ,Object> map=new HashMap<>();
        Integer userIds=null;
        if (userId!=null && !"".equals(userId)){
            userIds=Integer.parseInt(userId);
            User user = this.selectById(userId);
            //获取交易所用户id
            String userPhone = user.getUserPhone();
            String result = toolfeignInterface.getHHTBUserId(userPhone);
            String HHTBId="";
            if (!"error".equals(result)){
                JSONObject jsonObject = JSONObject.parseObject(result);
                if("true".equals(jsonObject.get("isSuc").toString())){
                    JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("datas").toString());
                    HHTBId=  jsonObject1.get("userID").toString();
                }
            }

            //获取HHTB余额
            String balance = toolfeignInterface.getBalance(HHTBId, "21");
            String HHTBBalance="";
            if (!"error".equals(balance)){
                JSONObject json = JSONObject.parseObject(balance);
                if("true".equals(json.get("isSuc").toString())){
                    JSONObject json1 = json.parseObject(json.get("datas").toString());
                    HHTBBalance=  json1.get("available").toString();
                }
            }

            if (HHTBBalance==null || "".equals(HHTBBalance)){
                HHTBBalance="0.0000";
            }
            //获取猫币余额
            String MAOC = toolfeignInterface.getBalance(HHTBId, "17");
            String MAOCBalance="";
            if (!"error".equals(MAOC)){
                JSONObject jsons = JSONObject.parseObject(MAOC);
                if("true".equals(jsons.get("isSuc").toString())){
                    JSONObject json1 = jsons.parseObject(jsons.get("datas").toString());
                    MAOCBalance=  json1.get("available").toString();
                }
            }

            if (MAOCBalance==null || "".equals(MAOCBalance)){
                MAOCBalance="0.0000";
            }
            Account account=new Account();
            account.setUserId(userIds);
            EntityWrapper<Account> entityWrapper=new  EntityWrapper<Account>(account);
            Account account1 = accountService.selectOne(entityWrapper);
            if (account1==null){
                map.put("code","00");
                map.put("msg","没有账户");

            }else{
                map.put("code","01");
                map.put("MAOCBalance",MAOCBalance);
                map.put("HHTBBalance",HHTBBalance);
                map.put("account",account1);
            }
        }else {
            map.put("code","00");
            map.put("msg","登录失败");
        }
        return map;
    }
    @Override
    public Map<String,Object> loginBycode(@PathVariable String userphone, String num){
        Map<String,Object> map=new HashMap<>();
        EntityWrapper ewp=new EntityWrapper();
        ewp.setEntity(new User());
        ewp.where("userPhone={0}", userphone);
        User user2 = this.selectOne(ewp);
        if (user2==null ){
            map.put("code","00");
            map.put("msg","该手机号未注册");
            return map;
        }
        //从缓存中获取短信验证码
        Object obj = cacheUtil.get("mb:"+userphone);
        if(obj != null){
            if(!obj.toString().equals(num)){
                map.put("code","00");
                map.put("msg","短信验证码错误");
                return map;
            }
        }else {
            map.put("code","00");
            map.put("msg","短信验证码失效");
            return map;
        }
        if (user2.getUserStatus()==0){
            map.put("code","00");
            map.put("msg","该用户已被锁定");
            return map;
        }

        String result = toolfeignInterface.getHHTBUserId(userphone);
        String HHTBId="";
        if (!"error".equals(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            if("true".equals(jsonObject.get("isSuc").toString())){
                JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("datas").toString());
                HHTBId=  jsonObject1.get("userID").toString();
            }
        }
        Map<String, Object> mmp = userMapper.selectLoginMessages(user2.getUserId());
//        UserDto userDto=new UserDto();
//        BeanUtils.copyProperties(user2,userDto);
        Object payPwd = mmp.get("payPwd");
        if(payPwd != null && !"".equals(payPwd.toString())){
//            userDto.setIsppwd(true);
            mmp.put("isppwd",true);
        }else {
//            userDto.setIsppwd(false);
            mmp.put("isppwd",false);
        }
//        Date createTime = user2.getCreateTime();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Object createTime = mmp.get("createTime");
        String format = dateFormat.format((Date)createTime);
//        userDto.setCreatetimes(format);
//        userDto.setHhtbId(HHTBId);
        mmp.put("createTime",format);
        mmp.put("HHTBId",HHTBId);
        cacheUtil.set("catCoinUserId",user2.getUserId());
        cacheUtil.set("catCoinUserName",user2.getUserName());
//        map.put("user",userDto);
        mmp.put("code","01");
        mmp.put("msg","登录成功");
        return mmp;
    }

    /**
     * 图片上传阿里云
     * @return
     * @throws IOException
     */
    @Override
    public Map<String,Object> upload(HttpServletRequest req){
        Map<String,Object> map = new HashMap<String, Object>();

        MultipartHttpServletRequest mReq  =  null;
        MultipartFile file = null;
        InputStream is = null ;
        OSSResultModel ossResult = null;
        String fileName = "";
        // 原始文件名   UEDITOR创建页面元素时的alt和title属性
        String originalFileName = "";

        try {
            mReq = (MultipartHttpServletRequest)req;
            // 从config.json中取得上传文件的ID
            file = mReq.getFile("file");
            // 取得文件的原
            fileName = file.getOriginalFilename();
            originalFileName = fileName;
            if(!StringUtils.isEmpty(fileName)){
                is = file.getInputStream();
                fileName = fileUtils.reName(fileName);
                ossResult = fileUtils.saveFile(fileName, is);
            } else {
                throw new IOException("文件名为空!");
            }

            String[] strings = new String[5];
            strings[0] = ossResult.getUrl();


            map.put("code","01");
            map.put("url",strings[0]);
        }
        catch (Exception e) {
            map.put("code","00");
            map.put("msg","图片上传失败");
            System.out.println("文件 "+fileName+" 上传失败!");
        }

        return map;
    }


    @Override
    public User recommendInfo(String userId){
        User user = this.selectById(Integer.parseInt(userId));
        User user1=null;
        if(user!=null){
            Inviteid inviteid = new Inviteid();
            inviteid.setUserPhone(user.getUserPhone());
            EntityWrapper entityWrapper = new EntityWrapper(inviteid);
            List<Inviteid> inviteidList = inviteidService.selectList(entityWrapper);
            if(inviteidList.size()!=0){
                User userNew = new User();
                userNew.setUserPhone(inviteidList.get(0).getInvitePhone());
                EntityWrapper entityWrapperNew = new EntityWrapper(userNew);
                List<User> listUser = this.selectList(entityWrapperNew);
                user1=listUser.get(0);
            }
        }
        return user1;
    }

    @Override
    public List<User> recommendList(Integer userId){
        User user = this.selectById(userId);
        Inviteid inviteid = new Inviteid();
        inviteid.setInvitePhone(user.getUserPhone());
        EntityWrapper entityWrapper = new EntityWrapper(inviteid);
        List<Inviteid> listInvited = inviteidService.selectList(entityWrapper);
        List<User>  listUser = new ArrayList<>();
        for (int i=0;i<listInvited.size();i++){
           User user1 = this.selectById(listInvited.get(i).getUserId());
            listUser.add(user1);
        }
        return listUser;
    }

    @Override
    public List<Map<String,Object>> recommendListNew(Integer userId) {
        User user = this.selectById(userId);
        Inviteid inviteid = new Inviteid();
        inviteid.setInvitePhone(user.getUserPhone());
        EntityWrapper entityWrapper = new EntityWrapper(inviteid);
        List<Inviteid> listInvited = inviteidService.selectList(entityWrapper);
        List<Map<String,Object>> list= new ArrayList<>();
        for (int i=0;i<listInvited.size();i++){
            list = userMapper.selectListAll(listInvited.get(i).getUserId());
        }
        return list;
    }

    @Override
    public Integer recommendListCount(Integer userId) {
        User user = this.selectById(userId);
        Inviteid inviteid = new Inviteid();
        inviteid.setInvitePhone(user.getUserPhone());
        EntityWrapper entityWrapper = new EntityWrapper(inviteid);
        List<Inviteid> listInvited = inviteidService.selectList(entityWrapper);
        List<Map<String,Object>> list= new ArrayList<>();
        for (int i=0;i<listInvited.size();i++){
            list = userMapper.selectListAll(listInvited.get(i).getUserId());
        }
        int num = list.size();
        return num;
    }

}
